package online.xuping.thousandsOfWorlds.config;

import online.xuping.thousandsOfWorlds.common.constants.Constants;
import online.xuping.thousandsOfWorlds.common.threadpool.ThreadPoolBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * ThreadPoolConfig 类是 定义项目中的线程池
 *
 * @author dongyinggang
 * @date 2021-01-12 15:06
 **/
@Configuration
public class ThreadPoolConfig {

    /**
     * 默认核心线程数 10
     */
    private static final int DEFAULT_CORE_POOL_SIZE = Constants.TEN_INT;
    /**
     * 默认最大线程数 10
     */
    private static final int DEFAULT_MAXIMUM_POOL_SIZE = Constants.TEN_INT;

    @Value("${eventThreadPool.capacityLength}")
    private int eventCapacityLength;

    @Value("${commonThreadPool.corePoolSize}")
    private int commonCapacityLength;

    /**
     * commonThreadPool 方法是 创建公共线程池,用于所有业务
     *
     * @return 公共线程池
     * @author dongyinggang
     * @date 2021/1/12 10:58
     */
    @Primary
    @Bean("commonThreadPool")
    public ExecutorService buildCommonThreadPool() {
        String prefix = "common";
        return ThreadPoolBuilder.build(prefix, DEFAULT_CORE_POOL_SIZE, DEFAULT_MAXIMUM_POOL_SIZE, commonCapacityLength);
    }

    /**
     * eventThreadPool 方法是 创建事件线程池,用于事件处理
     * 指定拒绝策略为CallerRunsPolicy,即由调用线程处理该任务
     *
     * @return 事件线程池
     * @date 2023/1/11 14:29
     * @author dongyinggang
     */
    @Bean("eventThreadPool")
    public ExecutorService buildEventThreadPool() {
        String prefix = "event";
        return ThreadPoolBuilder.build(prefix, Constants.TWO_INT, DEFAULT_MAXIMUM_POOL_SIZE,
                eventCapacityLength, new ThreadPoolExecutor.CallerRunsPolicy());
    }
}
